//
//  NewFilmViewController.m
//  TravelFollowYourHeart
//
//  Created by ENERGY on 2018/1/18.
//  Copyright © 2018年 Lwx. All rights reserved.
//

#define Border 10
#define bottomViewH 50
#import "NewFilmViewController.h"
#import "IWTextView.h"
#import "CRMediaPickerController.h"
#import "KZVideoViewController.h"
#import "AddressSelectedController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>

static NSString * const amapServiceKey = @"9fa9446d3fd67ff580e4694ed3e5aa6a";

@interface NewFilmViewController ()<UITableViewDelegate,UITableViewDataSource,CRMediaPickerControllerDelegate,KZVideoViewControllerDelegate, UIActionSheetDelegate>
@property(nonatomic, strong)UIView * bgView;
@property(nonatomic, strong)IWTextView * textView;
@property(nonatomic, strong)UITableView * tableView;
@property(nonatomic, strong)UIButton * addBtn;
@property(nonatomic, strong)UIButton * submitBtn;
@property(nonatomic, strong)CRMediaPickerController *vadioVc;
@property(nonatomic, strong)NSData * videoData;
@property(nonatomic, strong)UIView * bottomView;
@property(nonatomic, strong)UILabel * locationLab;
@property(nonatomic, strong)UIButton * locationBtn;
@end

@implementation NewFilmViewController(Networking)
- (void)submitTakeFilmContent{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"lng":@([LocationTool shareIntance].longitude),
                           @"lat":@([LocationTool shareIntance].latitude),
                           @"content":self.textView.text,
                           @"location":self.locationLab.text
                           };
    [self showprogressHUD];
    [[HttpRequest shardWebUtil]postNetworkRequestURLString:Url(@"/diary/writeVideo") andParas:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:self.videoData name:@"vic" fileName:[NSString stringWithFormat:@"%ld.mp4",self.videoData.length] mimeType:@"video/mp4"];
//        [[HUDHelper sharedInstance]tipMessage:@"视频审核中"];
//        [self.navigationController popViewControllerAnimated:YES];
    } andTransferGottenData:^(id obj, NSError *error) {
        if (error)
        {
            [self hiddenProgressHUD];
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }
        else
        {
            [self hiddenProgressHUD];
            if ([obj[@"code"] integerValue] == 100000) {
//                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
                [[HUDHelper sharedInstance]tipMessage:@"视频审核中"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}

@end

@implementation NewFilmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"新建美拍";
    self.view.backgroundColor = getColor(bgColor);
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.bottomView];
    [self.bottomView addSubview:self.locationBtn];
    [self.bottomView addSubview:self.locationLab];
    self.vadioVc = [[CRMediaPickerController alloc]init];
    self.vadioVc.delegate = self;
    self.vadioVc.mediaType = CRMediaPickerControllerMediaTypeVideo;
    self.vadioVc.sourceType = CRMediaPickerControllerSourceTypePhotoLibrary;
    self.vadioVc.allowsEditing = NO;
    self.vadioVc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    self.vadioVc.showsCameraControls = YES;
    self.videoData = [NSData alloc];
    //配置高德地图
    [AMapServices sharedServices].apiKey = amapServiceKey;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IWTextView *)textView{
    if (!_textView) {
        _textView = [[IWTextView alloc] initWithFrame:CGRectMake(Border, Border, SCREEN_WIDTH - 2*Border, 150)];
        _textView.placeholder = @"请输入内容……";
        _textView.font = DEF_FontSize_14;
//        _textView.backgroundColor = [UIColor redColor];
    }return _textView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _tableView.backgroundColor = getColor(bgColor);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        self.textView.frame = CGRectMake(Border, Border, SCREEN_WIDTH - 2*Border, 200);
        self.addBtn.frame = CGRectMake(Border, self.textView.bottom + Border, (SCREEN_WIDTH - 45) / 4, (SCREEN_WIDTH - 45) / 4);
        self.bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.addBtn.bottom + Border);
        self.submitBtn.frame = CGRectMake(15, _tableView.bottom - 64 - 60, SCREEN_WIDTH - 30, 40);
        [_tableView addSubview:self.bgView];
        [_tableView addSubview:self.textView];
        [_tableView addSubview:self.addBtn];
        [_tableView addSubview:self.submitBtn];
    }return _tableView;
}

- (UIButton *)addBtn{
    if (!_addBtn) {
        _addBtn = [[UIButton alloc] init];
        [_addBtn setImage:[UIImage imageNamed:@"fankui"] forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }return _addBtn;
}

- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = [UIColor whiteColor];
    }return _bgView;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.layer.cornerRadius = 8;
        _bottomView.layer.masksToBounds = YES;
        _bottomView.frame = CGRectMake(0, self.bgView.bottom + Border, SCREEN_WIDTH, bottomViewH);
    }return _bottomView;
}

- (UIButton *)locationBtn{
    if (!_locationBtn) {
        _locationBtn = [[UIButton alloc] init];
        _locationBtn.frame = CGRectMake(Border, Border, 85, self.bottomView.height - 2 * Border);
        [_locationBtn setImage:[UIImage imageNamed:@"yj_location"] forState:UIControlStateNormal];
        [_locationBtn setTitle:@"所在位置" forState:UIControlStateNormal];
        [_locationBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _locationBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
        [_locationBtn addTarget:self action:@selector(locationBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
    }return _locationBtn;
}

- (UILabel *)locationLab{
    if (!_locationLab) {
        _locationLab = [[UILabel alloc] init];
        _locationLab.font = DEF_FontSize_14;
        _locationLab.textColor = [UIColor blackColor];
        _locationLab.textAlignment = NSTextAlignmentLeft;
        _locationLab.frame = CGRectMake(self.locationBtn.right, Border, SCREEN_WIDTH - Border - self.locationBtn.right, self.bottomView.height - 2 * Border);
    }return _locationLab;
}

- (UIButton *)submitBtn{
    if (!_submitBtn) {
        _submitBtn = [[UIButton alloc] init];
        [_submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_submitBtn setTitle:@"提交" forState:UIControlStateNormal];
        _submitBtn.backgroundColor = getColor(@"ffbb02");
        _submitBtn.layer.cornerRadius = 8;
        _submitBtn.titleLabel.font = DEF_FontSize_14;
        _submitBtn.layer.masksToBounds = YES;
        [_submitBtn addTarget:self action:@selector(submitButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }return _submitBtn;
}

- (void)submitButtonAction{
    NSLog(@"提交");
    if (self.textView.text.length == 0) {
        [[HUDHelper sharedInstance]tipMessage:@"请添加说明"];
        return;
    }
    if (self.locationLab.text.length == 0) {
        [[HUDHelper sharedInstance]tipMessage:@"请选择位置"];
        return;
    }
    if (self.videoData == nil) {
        [[HUDHelper sharedInstance]tipMessage:@"请选择上传的视频"];
        return;
    }
    [self submitTakeFilmContent];
}

- (void)addBtnClick{
    NSLog(@"添加视频");
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加视频" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍摄小视频", @"从相册选择", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;//默认风格，灰色背景，白色文字
//    //获取按钮总数
//    NSString *num = [NSString stringWithFormat:@"%ld", actionSheet.numberOfButtons];
//    NSLog(@"%@", num);
//
//    //获取某个索引按钮的标题
//    NSString *btnTitle = [actionSheet buttonTitleAtIndex:1];
//    NSLog(@"%@", btnTitle);
    [actionSheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
//根据被点击的按钮做出反应，0对应destructiveButton，之后的button依次排序
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"拍摄");
        KZVideoViewController *vc = [[KZVideoViewController alloc]init];
        vc.delegate = self;
        [vc startAnimationWithType:KZVideoViewShowTypeSingle];
    }
    else if (buttonIndex == 1) {
        NSLog(@"相册");
        [self.vadioVc show];
    }
}


- (void)locationBtnClick{
    AddressSelectedController * addressSelectedVC = [[AddressSelectedController alloc] init];
    addressSelectedVC.completeBlock = ^(DDLocationReGeocode *reGeocode, NSError *error) {
        
        NSLog(@"%@,%@,%f,%f",reGeocode.name,reGeocode.address,reGeocode.coordinate.latitude,reGeocode.coordinate.longitude);
        self.locationLab.text = reGeocode.name;
    };
    addressSelectedVC.currentCoordinate = CLLocationCoordinate2DMake([LocationTool shareIntance].latitude,[LocationTool shareIntance].longitude);
    [self.navigationController pushViewController:addressSelectedVC animated:YES];
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.textView resignFirstResponder];
}


#pragma mark - KZVideoViewControllerDelegate
//截取视频图片
- (void)videoViewController:(KZVideoViewController *)videoController didRecordVideo:(KZVideoModel *)videoModel
{
    //视频数据
    NSData* data= [NSData dataWithContentsOfFile:videoModel.videoAbsolutePath];
    self.videoData = data;
    //用于介绍视频内容的截图
    UIImage * image = [UIImage getVadioImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:videoModel.thumAbsolutePath]]];
    [self.addBtn setImage:image forState:UIControlStateNormal];
}

- (void)videoViewControllerDidCancel:(KZVideoViewController *)videoController {
    NSLog(@"没有录到视频");
}

#pragma mark - CRMediaPickerControllerDelegate
//选取视频或图片后，返回到控制器的时候调用
- (void)CRMediaPickerController:(CRMediaPickerController *)mediaPickerController didFinishPickingAsset:(ALAsset *)asset error:(NSError *)error
{
    
    if (!error)
    {
        if (asset)
        {
            if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
            {
                //图片
            }
            else if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
            {
                //视频
                WS(ws);
                ALAssetRepresentation *rep = [asset defaultRepresentation];
                Byte *buffer = (Byte*)malloc((NSUInteger)rep.size);
                NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:(NSUInteger)rep.size error:nil];
                self.videoData = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
//                self.videoData = data;
                //视频截图
                NSString * urlStr = asset.defaultRepresentation.url.absoluteString;
                [self.addBtn setImage:[UIImage getImageFromVideoURLString:urlStr] forState:UIControlStateNormal];
            }
        }
        else
        {
            NSLog(@"没选择");
        }
    }
    else
    {
        NSLog(@"%@", error.localizedDescription);
    }
}

- (void)CRMediaPickerControllerDidCancel:(CRMediaPickerController *)mediaPickerController
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

@end
